/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Extasys;

import java.util.Arrays;

/**
 *
 * @author NSi
 */
public class ByteArrayBuilder
{

    private byte[] fBytes;
    private final Object fLock;

    public ByteArrayBuilder()
    {
        fLock = new Object();
        fBytes = new byte[0];
    }

    /**
     * Append data to ByteArrayBuilder
     *
     * @param data is the byte[] array to append
     */
    public void Append(byte[] data)
    {
        synchronized (fLock)
        {
            byte[] newArray = new byte[fBytes.length + data.length];
            System.arraycopy(fBytes, 0, newArray, 0, fBytes.length);
            System.arraycopy(data, 0, newArray, fBytes.length, data.length);
            fBytes = newArray;
        }
    }

    public int IndexOf(byte[] subArray)
    {
        synchronized (fLock)
        {
            int i = 0;
            int subArrayLength = subArray.length;

            // Find subArray in fBytes
            for (i = 0; i < fBytes.length; i++)
            {
                byte[] arrayToCompare = Arrays.copyOfRange(fBytes, i, i + subArrayLength);

                if (Arrays.equals(arrayToCompare, subArray))
                {
                    return i;
                }
            }

            return -1;
        }
    }

    public void Delete(int indexFrom, int indexTo)
    {
        synchronized (fLock)
        {

            byte[] firstPart = Arrays.copyOfRange(fBytes, 0, indexFrom);
            byte[] secondPart = Arrays.copyOfRange(fBytes, indexTo, fBytes.length);

            byte[] C = new byte[firstPart.length + secondPart.length];
            System.arraycopy(firstPart, 0, C, 0, firstPart.length);
            System.arraycopy(secondPart, 0, C, firstPart.length, secondPart.length);

            fBytes = C;

            /*
             * if (indexFrom > 0) { System.arraycopy(fBytes, 0, firstPart, 0,
             * indexFrom); }
             *
             * System.arraycopy(fBytes, indexTo, firstPart, 0, fBytes.length -
             * indexTo);
             *
             * byte[] C = new byte[firstPart.length + secondPart.length];
             * System.arraycopy(firstPart, 0, C, 0, firstPart.length);
             * System.arraycopy(secondPart, 0, C, firstPart.length,
             * secondPart.length);
             *
             * fBytes = C;
             */

        }
    }

    public byte[] SubList(int fromIndex, int toIndex)
    {
        synchronized (fLock)
        {
            return Arrays.copyOfRange(fBytes, fromIndex, toIndex);
        }
    }

    public void Dispose()
    {
        synchronized (fLock)
        {
            this.fBytes = new byte[0];
        }
    }
}
